const path = require('path');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('ffmpeg-static');
// 尝试重新获取 ffprobe 路径
const ffprobePath = require('ffprobe-static').path;

// 设置 ffmpeg 路径
ffmpeg.setFfmpegPath(ffmpegPath);
ffmpeg.setFfprobePath(ffprobePath);


async function createVideoFromImages(images, audioPath, outputPath) {
    // 检查每个图片文件是否存在
    for (const img of images) {
        if (!fs.existsSync(img)) {
            return Promise.reject(new Error(`文件 ${img} 不存在`));
        }
    }

    

    return new Promise(async (resolve, reject) => {
        // 确保输出目录存在
        const outputDir = path.dirname(outputPath);
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }

        const command = ffmpeg();
        let stderrData = '';

        // 修改图片输入选项，添加强制格式转换
        images.forEach((img) => {
            // Remove -f image2 to auto-detect format, or use -f webp if files are WEBP
            const inputOptions = [
                '-loop 1',
                '-t 5',
                // '-f image2',  // Remove this line to auto-detect
                '-r 25',
                '-probesize 50M',
                '-analyzeduration 100M',
                '-thread_queue_size 1024'
            ];
            console.log(`正在添加输入文件: ${img}`);
            command.input(img).inputOptions(inputOptions);
        });
        console.log(audioPath,'audioPath');
        
        // 添加音频输入
        const duration = 30;
        
        console.log('音频总时长:', duration);
        const startTime = 30;
        // 计算图片总时长
        const imageTotalDuration = 40;
        command.input(audioPath).inputOptions([`-ss ${startTime}`, `-t ${imageTotalDuration}`]);
        console.log(`音频开始时间: ${startTime}`, `音频总时长: ${imageTotalDuration}`);
        
        let complexFilter = [];
        images.forEach((img, index) => {
            complexFilter.push(`[${index}:v]format=yuv420p,setsar=1/1,scale=720:-2:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1/1[img${index}];`);
        })
        let complexFilterStr = '';
        complexFilter.forEach((itme,i) => {
            complexFilterStr = complexFilterStr + `[img${i}]`
        }); 
        complexFilterStr = complexFilterStr + `concat=n=${images?.length}:v=1:a=0[vout];`;
        complexFilter.push(complexFilterStr);
        complexFilter.push(`[${images?.length}:a]anull[aout]`);
        // 修改滤镜配置，统一SAR参数并添加音频映射
        // const complexFilter = [
        //     '[0:v]format=yuv420p,setsar=1/1,scale=720:-2:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1/1[img0];',
        //     // '[1:v]format=yuv420p,setsar=1/1,scale=720:-2:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1/1[img1];',
        //     // '[2:v]format=yuv420p,setsar=1/1,scale=720:-2:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1/1[img2];',
        //     // '[img0][img1][img2]concat=n=3:v=1:a=0[vout];',
        //     '[img0]concat=n=1:v=1:a=0[vout];',
        //     '[1:a]anull[aout]' // 映射音频流
        // ].join('');
        console.log(complexFilter,'complexFilter');
        complexFilter = complexFilter?.join('');

        command
            .complexFilter(complexFilter)
            .videoCodec('libx264')
            .outputOptions([
                '-pix_fmt yuv420p',
                '-fps_mode vfr',
                '-shortest',
                '-s 720x1280',
                '-y',
                '-map [vout]',
                '-map [aout]' // 显式映射音频输出
            ])
            .on('start', (cmd) => console.log('执行命令:', cmd))
            .on('progress', (progress) => {
                console.log(`进度: ${progress.timemark}`);
            })
            .on('stderr', (data) => {  // 新增：捕获标准错误
                stderrData += data.toString();
                console.error('FFmpeg 输出:', data.toString());
            })
            .on('error', (err, stdout, stderr) => {
                console.error('完整错误输出:', stderrData);
                reject(new Error(`FFmpeg 错误: ${err.message}\n${stderrData}`));
            })
            .on('end', () => {
                console.log('视频生成成功');
                resolve(true);
            })
            .on('error', (err, stdout, stderr) => {
                console.error('完整错误输出:', stderrData);
                resolve(false);
            })
            .save(outputPath);
    });
}

// 新增时间格式转换函数
function parseTimemark(timemark) {
    const parts = timemark.split(':');
    return (+parts[0]) * 3600 + (+parts[1]) * 60 + (+parts[2]);
}

function getAudioDuration(audioPath) {
    // console.log(ffmpeg.ffprobe(audioPath),'ffmpeg');
    
    // return new Promise((resolve, reject) => {
    //     ffmpeg.ffprobe(audioPath, (err, metadata) => {
    //         if (err) {
    //             console.error('获取音频时长时出错:', err);
    //             reject(new Error(`获取音频 ${audioPath} 时长失败: ${err.message}`));
    //         } else if (!metadata || !metadata.format || typeof metadata.format.duration === 'undefined') {
    //             console.error('无法从元数据中获取音频时长:', metadata);
    //             reject(new Error(`无法从元数据中获取音频 ${audioPath} 时长`));
    //         } else {
    //             resolve(metadata.format.duration);
    //         }
    //     });
    // });
}



module.exports = {
    createVideoFromImages,
}